using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class door : MonoBehaviour
{
    public GameObject stoneDoor;
    private Rigidbody2D rb2d;
    private int coroutineId = 0;
    public AudioSource audiosource;
    // Start is called before the first frame update


    private void Awake()
    {
       rb2d = stoneDoor.GetComponent<Rigidbody2D>();
    }

    public void OnTriggerEnter2D(Collider2D collision)
    {
        rb2d.gravityScale = 1;
        audiosource.Play();
        StartCoroutine(ChangeColor(Color.red, false) );
    }

    IEnumerator ChangeColor(Color color , bool up)
    {
        Vector3 deltaV;
        if (up)
        {
            deltaV = new Vector3(0, 0.2f, 0);
        }
        else
        {
            deltaV = new Vector3(0, -0.2f, 0);
        }
        coroutineId++;
        int id = coroutineId;
        SpriteRenderer sr = GetComponent<SpriteRenderer>();
        float time = 0;
        Color deltaColor = color - sr.color;
        while (time < 0.5f && id == coroutineId)
        {
            time += Time.deltaTime;
            transform.position += deltaV * Time.deltaTime;
            sr.color += deltaColor * (Time.deltaTime / 0.5f);
            yield return null;
        }
        if (id == coroutineId)
        { sr.color = color; }
    }

    public void OnTriggerExit2D(Collider2D collision)
    {
        rb2d.gravityScale = -1;
        StartCoroutine(ChangeColor(Color.white, true));
    }
}
